from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from LogisticsCard.models import Cards

@login_required
def index_view(request: HttpRequest) -> HttpResponse:
    """
    渲染首页视图。
    """
    from LogisticsCard.models import CardUserRelation, Customer
    user = request.user
    # 只显示管理员和普通用户
    if hasattr(user, 'profile') and user.profile.type in ['admin', 'user']:
        if user.profile.type == 'admin':
            cards_count = Cards.objects.filter(delete_at__isnull=True).count()
        else:
            # 普通用户统计所有关联客户的卡数量
            customers = Customer.objects.filter(user=user, delete_at__isnull=True)
            card_ids = CardUserRelation.objects.filter(customer__in=customers, delete_at__isnull=True).values_list('card_id', flat=True)
            cards_count = Cards.objects.filter(id__in=card_ids, delete_at__isnull=True).count()
    else:
        cards_count = '-'  # 其它角色不显示
    return render(request, 'index.html', {'cards_count': cards_count})
